Inter Thread Communication
C# supports interthread communication with the Wait( ), Pulse( ), and PulseAll( ) methods. The Wait( ), Pulse( ), and PulseAll( ) methods are defined by the Monitor class. These methods can be called only from within a locked block of code. When a thread is temporarily blocked from running, it calls Wait( ). The sleeping thread is awakened when some other thread calls Pulse( ) or PulseAll( ). A call to Pulse( ) resumes the first thread in the queue of threads waiting for the lock. A call to PulseAll( ) signals the release of the lock to all waiting threads.
Syntax:
public static bool Wait(object waitOb)
public static bool Wait(object waitOb, int milliseconds)
public static void Pulse(object waitOb)
public static void PulseAll(object waitOb)
Exception:
A SynchronizationLockException will be thrown if Wait( ), Pulse( ), or PulseAll( ) is called from code that is not within a lock block.
Program on inter thread communication
using System;
using System.Threading;
class abc
{
public void get(bool running)
{
lock (this)
{
if (!running)
{
Monitor.Pulse(this); // notify any waiting threads
return;
}
Console.Write("Vision ");
Monitor.Pulse(this);
Monitor.Wait(this);
}
}
public void put(bool running)
{
lock (this)
{
if (!running)
{
Monitor.Pulse(this);
return;
}
Console.WriteLine("Computers");
Monitor.Pulse(this);
Monitor.Wait(this);
}
}
}
class xyz
{
public Thread thrd;
abc x;
public xyz(string name, abc t)
{
thrd = new Thread(this.run);
x = t;
thrd.Name = name;
thrd.Start();
}
void run()
{
for (int i = 0; i < 5; i++)
{
x.get(true);
}
x.get(false);
}
}
class pqr
{
public Thread thrd;
abc x;
public pqr(string name, abc t)
{
thrd = new Thread(this.run);
x = t;
thrd.Name = name;
thrd.Start();
}
void run()
{
for (int i = 0; i < 5; i++)
{
x.put(true);
}
x.put(false);
}
}
class inter
{
public static void Main()
{
abc x = new abc();
xyz mt1 = new xyz("Vision", x);
pqr mt2 = new pqr("Computers", x);
mt1.thrd.Join();
mt2.thrd.Join();
Console.WriteLine(" Stopped");
}
}